package cn.autumnorange.user.controller;

import cn.autumnorange.commons.util.StringUtils;
import cn.autumnorange.dto.UserDetailDto;
import cn.autumnorange.user.entity.AdminEntity;
import cn.autumnorange.user.entity.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@Transactional()
@RestController
public class UserController {
    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;
    //
    //    @Autowired
    //    private UserService userService;

    //    @GetMapping("/findUserByNameLike/{name}")
    //    public List<UserEntity> findUserByNameLike(@PathVariable String name) {
    //        return userService.findUserByNameLike("%" + name + "%");
    //    }

    //  @PostMapping("/saveUser")
    //  public void saveUser(@RequestBody UserEntity userEntity) {
    //    userService.saveUser(userEntity);
    //  }

    @ResponseBody
    @PreAuthorize("hasRole('ROLE_admin')")
    @RequestMapping("/saveAdmin")
    public JsonResult saveAdmin(@RequestBody AdminEntity adminEntity) {
        if (StringUtils.trimToNull(adminEntity.getId()) == null) {
            return new JsonResult("500", "id不能为空", null);
        }
        userDetailsServiceImpl.saveAdmin(adminEntity);
        return new JsonResult("200", "", adminEntity);
    }

    @ResponseBody
    @RequestMapping("/addAdmin")
    public JsonResult addAdmin(@RequestBody AdminEntity adminEntity) {
        if (StringUtils.trimToNull(adminEntity.getId()) != null) {
            return new JsonResult("500", "id必须为空", null);
        }
        adminEntity.setId(null);
        userDetailsServiceImpl.saveAdmin(adminEntity);
        return new JsonResult("200", "", adminEntity);
    }

    @ResponseBody
    @RequestMapping("/userDetailsService")
    public UserDetailDto userDetailsService(
            @RequestParam(value = "name", defaultValue = "admin") String name) {
        UserDetailDto userDetailsService = userDetailsServiceImpl.loadUserByUsername(name);
        return userDetailsService;
    }
}
